package com.hj.springframework3.with.tx;

import com.hj.springframework3.JdbcTestBase;
import com.hj.springframework3.annotation.Autowired;
import com.hj.springframework3.annotation.Component;
import com.hj.springframework3.annotation.Transactional;
import com.hj.springframework3.jdbc.JdbcTemplate;

import java.util.List;

/**
 * @Author : hujing
 * @Date: 2025/7/14 10:54
 * @Description:
 */
@Component
@Transactional
public class AddressService {
    @Autowired
    UserService userService;
    @Autowired
    JdbcTemplate jdbcTemplate;
    
    // 增加地址
    public void addAddress(Address... addresses){
        for (Address address : addresses) {
            // 查询用户是否存在
            userService.getUser(address.userId);
            jdbcTemplate.update(JdbcTestBase.INSERT_ADDRESS,address.userId,address.address,address.zip);
        }
    }
    
    // 获取地址
    public List<Address> getAddresses(int userId){
        return jdbcTemplate.queryForList(JdbcTestBase.SELECT_ADDRESS_BY_USERID,Address.class,userId);
    }
    
    // 删除地址
    public void deleteAddress(int userId){
        jdbcTemplate.update(JdbcTestBase.DELETE_ADDRESS_BY_USERID,userId);
        if (userId == 1){
            throw new RuntimeException("不能删除id为1的用户地址");
        }
    }
}
